package com.example.netty.client.udp;

import java.net.InetAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UdpClientCache {

    private static final Map<String, UdpClient> clientCache = new ConcurrentHashMap<>(128);

    private static final Object lock = new Object();


    public static UdpClient getClient(String ip, int port, int bindPort) throws Exception {
        String key = String.format("%s_%d", ip, port);
        boolean reachable = InetAddress.getByName(ip).isReachable(1000); //ping 判断网络是否通畅，以免短时间多次重连端口占用不可用
        synchronized (lock) {
            if (reachable) {
                if (!clientCache.containsKey(key)) {
                    UdpClient udpClient = new UdpClient(ip, port, bindPort);
                    clientCache.put(key, udpClient);
                }
                return clientCache.get(key);

            } else {
                throw new Exception(String.format("(%s)网络异常！", ip));
            }
        }
    }
}
